package com.sky.controller.notify;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.sky.properties.WeChatProperties;
import com.sky.service.OrderService;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * 支付回调接口
 */
@RestController
@RequestMapping("/notify")
@Api(tags="支付回调相关接口")
@Slf4j
public class PayNotifyController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 读取servlet数据
     * @param httpServletRequest
     * @return
     * @throws Exception
     */
    private String readData(HttpServletRequest httpServletRequest) throws Exception{
        BufferedReader bufferedReader=httpServletRequest.getReader();
        StringBuilder result=new StringBuilder();
        String line=null;
        while((line=bufferedReader.readLine())!=null){
            if(result.length()>0){
                result.append("\n");
            }
            result.append(line);
        }
        return result.toString();
    }

    /**
     * 数据解密
     * @param body
     * @return
     */
    private String decryptData(String body) throws Exception{
        JSONObject jsonResult = JSONObject.parseObject(body);
        JSONObject resource = jsonResult.getJSONObject("resource");
        String ciphertext = resource.getString("ciphertext");
        String nonce = resource.getString("nonce");
        String associatedData = resource.getString("associated_data");
        AesUtil aesUtil = new AesUtil(weChatProperties.getApiV3Key().getBytes(StandardCharsets.UTF_8));
        String plainText = aesUtil.decryptToString(associatedData.getBytes(StandardCharsets.UTF_8),
                nonce.getBytes(StandardCharsets.UTF_8),
                ciphertext);
        return plainText;
    }

    /**
     * 给微信响应
     * @param httpServletResponse
     * @throws Exception
     */
    private void response2Wechat(HttpServletResponse httpServletResponse) throws Exception{
        httpServletResponse.setStatus(200);
        HashMap<Object,Object> claims = new HashMap<>();
        claims.put("code","SUCCESS");
        claims.put("message","SUCCESS");
        httpServletResponse.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
        httpServletResponse.getOutputStream().write(JSONUtils.toJSONString(claims).getBytes(StandardCharsets.UTF_8));
        httpServletResponse.flushBuffer();
    }

    /**
     * 支付成功回调
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/paySuccess")
    @ApiOperation("支付成功回调")
    public void paySuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception{
        //读取数据
        String body=readData(httpServletRequest);
        log.info("支付成功回调：{}",body);
        //数据解密
        String plainText=decryptData(body);
        log.info("密文解密后：{}",plainText);
        JSONObject jsonObject=JSONObject.parseObject(plainText);
        String outTradeNo=jsonObject.getString("out_trade_no"); //获取商户平台订单号
        String transactionId=jsonObject.getString("transaction_id"); //微信支付交易号
        log.info("商户平台订单号：{}",outTradeNo);
        log.info("微信支付交易号：{}",transactionId);
        //订单业务处理
        orderService.paySuccess(outTradeNo);
        //微信响应
        response2Wechat(httpServletResponse);
    }

}
